/**
 * @file key_scan.c
 * @brief 按键扫描
 *
 * @author 刘伟
 *
 * @date 2022-05-08
 *
 * @copyright 海南大学 - 追光者
 */

#include <rtthread.h>
#include <rtdevice.h>
#include "drv_common.h"
#include "app_main.h"

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

#define PRESS(key) !rt_pin_read(key)

void key_scan(void *params)
{
    while (1)
    {
        if (PRESS(KEY0_PIN) || PRESS(KEY1_PIN) || PRESS(KEY2_PIN))
        {
            rt_uint32_t e = 0;
            rt_thread_mdelay(10);
            if (PRESS(KEY0_PIN))
            {
                e |= EVENT_PRESS_KEY0;
            }
            if (PRESS(KEY1_PIN))
            {
                e |= EVENT_PRESS_KEY1;
            }
            if (PRESS(KEY2_PIN))
            {
                e |= EVENT_PRESS_KEY2;
            }
            rt_event_send(s_event, e);
        }
        rt_thread_mdelay(100);
        if (!PRESS(KEY0_PIN))
        {
            rt_event_recv(s_event, EVENT_PRESS_KEY0, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, 0, NULL);
        }
        if (!PRESS(KEY1_PIN))
        {
            rt_event_recv(s_event, EVENT_PRESS_KEY1, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, 0, NULL);
        }
        if (!PRESS(KEY2_PIN))
        {
            rt_event_recv(s_event, EVENT_PRESS_KEY2, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, 0, NULL);
        }
    }
}

int key_init(void)
{
    rt_pin_mode(KEY0_PIN, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY1_PIN, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY2_PIN, PIN_MODE_INPUT_PULLUP);

    rt_thread_t thread = rt_thread_create("key_scan", key_scan, NULL, 512, PRIO_KEY_SCAN, 10);
    rt_thread_startup(thread);

    return 0;
}
INIT_DEVICE_EXPORT(key_init);
